// pages/2411Ayiliao-pages/recharge/detail.js
Page({
	data: {
		rechargeData: {
			id: '',
			amount: '+500.00',
			cardNumber: '39000909000000',
			paymentMethod: '微信支付',
			paymentTime: '2020-12-26 10:06:45',
			orderNumber: 'CZ202012261006450001',
			type: '就诊卡充值',
			balance: '0.00',
			status: 'success',
			statusText: '充值成功'
		},
		loading: false,
		showTestButtons: false // 开发时设置为true来显示测试按钮
	},

	onLoad(options) {
		if (options.data) {
			try {
				const data = JSON.parse(decodeURIComponent(options.data))
				this.setData({
					rechargeData: {
						...this.data.rechargeData,
						...data
					}
				})
			} catch (e) {
				console.error('解析数据失败:', e)
				wx.showToast({
					title: '数据解析失败',
					icon: 'none'
				})
			}
		} else if (options.id) {
			// 如果有ID参数，从服务器获取详细信息
			this.loadRechargeDetail(options.id)
		}
	},

	// 从服务器加载充值详情
	loadRechargeDetail(rechargeId) {
		this.setData({
			loading: true
		})

		wx.showLoading({
			title: '加载中...'
		})

		wx.request({
			url: `http://localhost:8084/recharge/detail/${rechargeId}`,
			method: 'GET',
			header: {
				'Content-Type': 'application/json',
				'Authorization': wx.getStorageSync('token') || ''
			},
			success: (res) => {
				wx.hideLoading()
				this.setData({
					loading: false
				})

				if (res.statusCode === 200 && res.data) {
					let detailData = res.data

					// 处理数据格式
					if (typeof detailData === 'string') {
						try {
							detailData = JSON.parse(detailData)
						} catch (e) {
							console.error('JSON解析失败:', e)
							this.showError('数据格式错误')
							return
						}
					}

					// 检查是否为Result格式的响应
					if (detailData.code !== undefined) {
						if (detailData.code !== 200) {
							console.error('后端返回错误:', detailData.message)
							this.showError(detailData.message || '请求失败')
							return
						}
						// 从Result.data中提取实际数据
						detailData = detailData.data
					}

					// 处理详情数据
					const processedData = {
						id: detailData.id || detailData.rechargeId || rechargeId,
						amount: detailData.amount > 0 ? `+${detailData.amount.toFixed(2)}` : `${detailData.amount.toFixed(2)}`,
						cardNumber: detailData.cardNumber || detailData.cardNo || '39000909000000',
						paymentMethod: detailData.paymentMethod || detailData.payMethod || '微信支付',
						paymentTime: this.formatTime(detailData.paymentTime || detailData.createTime || detailData.time),
						orderNumber: detailData.orderNumber || detailData.orderNo || 'CZ202012261006450001',
						type: detailData.type || detailData.rechargeType || '就诊卡充值',
						balance: detailData.balance ? detailData.balance.toFixed(2) : '0.00',
						status: detailData.status || 'success',
						statusText: this.getStatusText(detailData.status || 'success')
					}

					this.setData({
						rechargeData: processedData
					})
				} else {
					console.error('加载充值详情失败:', res.statusCode, res.data)
					this.showError(`请求失败: ${res.statusCode}`)
				}
			},
			fail: (error) => {
				wx.hideLoading()
				this.setData({
					loading: false
				})
				console.error('网络请求失败:', error)
				this.showError('网络请求失败')
			}
		})
	},

	// 格式化时间
	formatTime(timeStr) {
		if (!timeStr) return '未知时间'
		
		try {
			const date = new Date(timeStr)
			if (isNaN(date.getTime())) {
				return timeStr
			}
			
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hour = String(date.getHours()).padStart(2, '0')
			const minute = String(date.getMinutes()).padStart(2, '0')
			const second = String(date.getSeconds()).padStart(2, '0')
			
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`
		} catch (e) {
			return timeStr
		}
	},

	// 获取状态文本
	getStatusText(status) {
		const statusMap = {
			'success': '充值成功',
			'failed': '充值失败',
			'pending': '处理中',
			'cancelled': '已取消',
			'refunded': '已退款'
		}
		return statusMap[status] || '未知状态'
	},

	// 显示错误信息
	showError(message) {
		wx.showToast({
			title: message,
			icon: 'none',
			duration: 2000
		})
	},

	// 复制订单号
	copyOrderNumber() {
		wx.setClipboardData({
			data: this.data.rechargeData.orderNumber,
			success: () => {
				wx.showToast({
					title: '订单号已复制',
					icon: 'success'
				})
			}
		})
	},

	// 复制卡号
	copyCardNumber() {
		wx.setClipboardData({
			data: this.data.rechargeData.cardNumber,
			success: () => {
				wx.showToast({
					title: '卡号已复制',
					icon: 'success'
				})
			}
		})
	},

	// 返回列表
	goBack() {
		console.log('点击返回列表按钮')
		
		// 检查页面栈
		const pages = getCurrentPages()
		console.log('当前页面栈:', pages.length, '页')
		
		if (pages.length > 1) {
			// 有上一页，使用navigateBack
			wx.navigateBack({
				delta: 1,
				success: () => {
					console.log('返回列表成功')
				},
				fail: (error) => {
					console.error('返回列表失败:', error)
					this.fallbackToOutpatient()
				}
			})
		} else {
			// 没有上一页，直接跳转
			this.fallbackToOutpatient()
		}
	},

	// 备用返回方法
	fallbackToOutpatient() {
		console.log('尝试重定向到outpatient页面')
		
		// 尝试不同的路径格式
		const paths = [
			'/pages/2411Ayiliao-pages/recharge/outpatient',
			'../outpatient/outpatient',
			'../../recharge/outpatient',
			'/recharge/outpatient'
		]
		
		const tryPath = (index) => {
			if (index >= paths.length) {
				console.error('所有路径都失败了')
				wx.showToast({
					title: '返回失败，请手动返回',
					icon: 'none',
					duration: 2000
				})
				return
			}
			
			const path = paths[index]
			console.log(`尝试路径: ${path}`)
			
			wx.redirectTo({
				url: path,
				success: () => {
					console.log(`✅ 重定向成功，使用路径: ${path}`)
				},
				fail: (error) => {
					console.error(`❌ 路径 ${path} 失败:`, error)
					tryPath(index + 1)
				}
			})
		}
		
		tryPath(0)
	},

	// 测试navigateBack
	testNavigateBack() {
		console.log('测试navigateBack')
		wx.navigateBack({
			delta: 1,
			success: () => {
				wx.showToast({
					title: 'navigateBack成功',
					icon: 'success'
				})
			},
			fail: (error) => {
				console.error('navigateBack失败:', error)
				wx.showToast({
					title: 'navigateBack失败',
					icon: 'none'
				})
			}
		})
	},

	// 测试redirectTo
	testRedirectTo() {
		console.log('测试redirectTo')
		wx.redirectTo({
			url: '/pages/2411Ayiliao-pages/recharge/outpatient',
			success: () => {
				wx.showToast({
					title: 'redirectTo成功',
					icon: 'success'
				})
			},
			fail: (error) => {
				console.error('redirectTo失败:', error)
				wx.showToast({
					title: 'redirectTo失败',
					icon: 'none'
				})
			}
		})
	},

	// 测试switchTab
	testSwitchTab() {
		console.log('测试switchTab')
		wx.switchTab({
			url: '/pages/2411Ayiliao-pages/recharge/outpatient',
			success: () => {
				wx.showToast({
					title: 'switchTab成功',
					icon: 'success'
				})
			},
			fail: (error) => {
				console.error('switchTab失败:', error)
				wx.showToast({
					title: 'switchTab失败',
					icon: 'none'
				})
			}
		})
	},

	// 分享
	onShareAppMessage() {
		return {
			title: '充值记录详情',
			path: '/pages/2411Ayiliao-pages/recharge/detail'
		}
	}
}) 